/**
 * Created by hjqi on 2016/2/5.
 */
var http = require('http');
var qs = require('querystring');
var url = require('url');
var OAuthMgr = require('./oauth_mgr');
var crypto = require('crypto');
var tokenMap = {};
var st2urlMap = {};

http.createServer(function (req, res) {

    var _url = url.parse(req.url);
    var param = qs.parse(_url.query);

    if (req.url.indexOf('code') !== -1) {
        processCode(req, res,_url);
    }else if(req.url.indexOf('type') !== -1 && param.type !== undefined && param.myst === undefined){
        requestAuth(req, res,_url);
    }else if(req.url.indexOf('myst') !== -1 && param.myst !== undefined){
        var _key = param.myst;
        console.log('key is '+_key);
        console.log('token  is '+tokenMap[_key]);
        res.end(tokenMap[_key]);
    }
    else{
        res.writeHead(200, {
            'Content-Type': 'text/html' });
        res.end('welcome!');
    }

}).listen(8899);

function requestAuth(req, res,requrl){

    var param = qs.parse(requrl.query);
    var oauth2 = undefined;
    oauth2 = OAuthMgr.getOAuth(param.type);

    if( oauth2 !== undefined){

        //TODO 302 to authURL
        var _urlAndSt = oauth2.getReqAuthUrlAndSt();
        res.writeHead(302, {
            'Content-Type': 'text/html',
            'Location':_urlAndSt.url});
        res.end();
        st2urlMap[_urlAndSt.st] = requrl.path;
    }else{
        res.writeHead(200, {
            'Content-Type': 'text/html' });
        res.end('not found type');
        return;
    }

}

function processCode(req, res,requrl){

    var qsObj = qs.parse(requrl.query);
    var _ret_st = qsObj.state;
    var _url = st2urlMap[_ret_st];
    var oauth2 = undefined;
    //var _queryStr = 'id='+id;
    if (req.url.indexOf('github') !== -1) {
        oauth2 = OAuthMgr.getOAuth('github');
        //_queryStr += '&type=github';
    }else if(req.url.indexOf('bitbucket') !== -1){
        oauth2 = OAuthMgr.getOAuth('bitbucket');
        //_queryStr += '&type=bitbucket';
    }else{
        res.end();
        return;
    }

    if(oauth2 !== undefined){
        /** Obtaining access_token */
        oauth2._oauth2.getOAuthAccessToken(
            qsObj.code,
            oauth2._accessTokenParam,
            function (e, access_token, refresh_token, results){
                if (e) {
                    console.log(e);
                    res.end(e);
                } else if (results.error) {
                    console.log(results);
                    res.end(JSON.stringify(results));
                }
                else {
                    console.log('Obtained access_token: ', access_token);
                    var _st = crypto.randomBytes(16).toString('hex');
                    tokenMap[_st] = access_token;
                    res.writeHead(302, {
                        'Content-Type': 'text/html',
                        //TODO replace hardcode url
                        //'Location':'http://localhost:9000/apiGit/ReqRepoList?myst='+_st+'&'+_queryStr});
                        'Location':'http://localhost:9000'+_url+'&myst='+_st});
                    res.end();
                }
            });
    }else {
        res.end('error');
        return;
    }

}